import React from 'react';
import HttpRequest from './../HttpRequest.js';
import Button from "../../../../node_modules/react-bootstrap/lib/Button";
import AddMemberDlg from "./addMemberDialog.jsx";
import Input from '../../../../node_modules/react-bootstrap/lib/Input';
import OverlayTrigger from "react-bootstrap/lib/OverlayTrigger";
import Popover from "react-bootstrap/lib/Popover";
import msgFrontAgent from  '../msgFrontAgent.js';


var MemberManageTab = React.createClass({
        getInitialState: function () {
            return ({
                current_project: this.props.current_project,
                members: []
            });
        },
        componentWillReceiveProps: function (newProps) {
            this.setState({
                current_project: newProps.current_project
            }, this.componentWillMount);
        },
        getUserMatched: function () {
            if (document.getElementById("autocomplete").value) {
                HttpRequest.searchUsers(document.getElementById("autocomplete").value).success(function (resp) {
                    if (resp.code == 0) {
                        let data = resp.data;
                        let users = [];
                        data.map(function (user) {
                            users.push(user.loginname);
                        });
                        $("#autocomplete").autocomplete({
                            minLength: 0,
                            source: function (request, response) {
                                var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
                                response($.grep(users, function (item) {
                                    return matcher.test(item);
                                }));
                            }
                        });
                    }
                }).error()
            }

        },
        componentWillMount: function () {
            var projectMembers = [];
            var level = 0;
            var that = this;
            HttpRequest.getMembers(that.state.current_project._id).success(function (msg) {
                if (msg.code == 0) {
                    let owner;
                    let user_short_ids = [];
                    msg.data.map((member)=> {
                        user_short_ids.push(member.user);
                    });
                    HttpRequest.getMembersByShortIdArr({"shortid": user_short_ids}).success(function (members) {
                        let user_info = members.data;
                        msg.data.map((member)=> {
                            for (var user in user_info) {
                                if (user_info[user].shortid == member.user) {
                                    member['loginname'] = user_info[user].loginname;
                                    break;
                                }
                            }
                            let name = member.loginname;
                            let role = member.role;
                            let shortid = member.user;
                            let _id = member._id;
                            let ob = {'name': name, 'role': role, 'shortid': shortid, '_id': _id};
                            if (role != "owner") {
                                projectMembers.push(ob);
                            } else {
                                owner = ob;
                            }
                        });
                        if(typeof (owner) != "undefined"){
                            projectMembers.splice(0, 0, owner);
                        }
                        HttpRequest.getCurrentUser().success(function (res) {
                            if (res.code == 0) {
                                let name = res.data.shortid;
                                projectMembers.map(function (member) {
                                    if (member.shortid == name) {
                                        switch (member.role) {
                                            case "owner":
                                                level = 4;
                                                break;
                                            case "admin":
                                                level = 3;
                                                break;
                                            case "developer":
                                                level = 2;
                                                break;
                                            case "observer":
                                                level = 1;
                                                break;
                                        }
                                    }
                                });
                                that.setState({
                                    members: projectMembers,
                                    selectedIndex: null,
                                    level: level
                                }, that._renderTableItems);
                            }
                        });
                    }).error();
                }
            }).error(function (msg) {
                console.log("获取项目成员失败" + msg);
            });
        },
        onItemSelected: function (item, index, e) {
            for (var i = 0; i < this.state.members.length; i++) {
                if (index != i) {
                    document.getElementById("member_role_" + i).style.display = "inline";
                    document.getElementById("edit_role_" + i).style.display = "none";

                }
            }
            this.setState({"selectedIndex": index}, this._renderTableItems);
        }
        ,
        openAddMemberDlg: function () {
            this.refs["add_member_dialog"].handleOpen(this.props.current_project);
        }
        ,
        addMember: function (data, user_info, create_wkp) {
            var that = this;
            HttpRequest.addMember(data).success(function (msg) {
                if (msg.code == 500) {
                    toastr.error(null, "添加成员失败:" + JSON.stringify(msg.message));
                } else if(msg.code == 204 ){
                    toastr.warning(null, msg.message);
                }else {
                    this.componentWillMount();
                    if (create_wkp) {
                        toastr.success(null, "用户添加成功，开始创建工作空间");
                        var options = {
                            work_name: that.props.current_project.name + '_' + user_info.loginname,
                            project_id: JSON.parse(msg.data).data.projectId,
                            //git_source: 1,
                            //git_url: "git@10.2.9.96:" + that.props.current_project.name,
                            userId: JSON.parse(msg.data).data.user,
                            userName: user_info.loginname
                        };
                        HttpRequest.addWorkspace(options).success(function (res) {
                            if (res.code == 200) {
                                toastr.success(null, "工作空间开始创建");
                                msgFrontAgent.order(res.data.task_id, function (data) {
                                    if (data.err) {
                                        toastr.error(null, data.err, {timeOut: 0});
                                    } else {
                                        toastr.success(null, data.body.msg);
                                    }
                                });
                            } else {
                                toastr.error(null, "工作空间创建错误");
                            }
                        }).error(function (error) {
                            toastr.error(null, "工作空间创建错误");
                        });

                    }

                }
            }.bind(this)).error(function (msg) {
                toastr.error(null, "添加成员失败:" + JSON.stringify(msg.message));
            });
        }
        ,
        removeMember: function (item) {
            //var memberId = [];
            //memberId.push(item._id);
            var data = {
                member_id: item._id,
                project_id:this.state.current_project._id
            }
            confirm("确定删除？", function () {
                HttpRequest.removeMember(data).success(function (res) {
                    if (res.data.code == 200) {
                        this.componentWillMount();
                        toastr.success(null, res.data.data);
                    } else {
                        toastr.error(null, res.data.message);
                    }

                }.bind(this)).error(function (msg) {
                    toastr.error(null, "删除成员失败！");
                });
            }.bind(this))
        }
        ,
        saveEdit: function (item, index) {
            var data = {
                _id: item._id,
                role: document.getElementById('edit_role_select_' + index).value
            };
            HttpRequest.updateMember(data).success(function (msg) {
                if (msg.code == 500) {
                    toastr.error(null, "编辑成员失败:" + JSON.stringify(msg.message));
                } else {
                    toastr.success(null, "编辑成员成功");
                    this.componentWillMount();
                }
            }.bind(this)).error(function (msg) {
                toastr.error(null, "编辑成员失败");
            });
            document.getElementById("member_role_" + index).style.display = "inline";
            document.getElementById("edit_role_" + index).style.display = "none";
        }
        ,
        editRole: function (item, index, e) {

            //for (var i = 0; i < this.state.members.length; i++) {
            //    if (index != i) {
            //        document.getElementById("member_role_" + i).style.display = "inline";
            //        document.getElementById("edit_role_" + i).style.display = "none";
            //    }
            //}
            document.getElementById("member_role_" + index).style.display = "none";
            document.getElementById("edit_role_" + index).style.display = "inline";
            this.setState({"selectedIndex": index}, this._renderTableItems);
            document.getElementById("edit_role_select_" + index).focus();
            e.stopPropagation();
        },
        hiddenSelect: function (index) {
            setTimeout(function () {
                document.getElementById("member_role_" + index).style.display = "inline";
                document.getElementById("edit_role_" + index).style.display = "none";
            }, 250);
        },
        _renderTableItems: function () {
            var table_item = [];
            var selectedStyle = {
                backgroundColor: "#f3f3f3",
                opacity: "0.8",
                borderBottom: "#f2f2f2 1px solid",
                height: "50px",
                fontSize: "15px"
            };
            this.state.members.map(function (item, index) {
                var style = {borderBottom: "#f2f2f2 1px solid", height: "50px", fontSize: "15px"};
                var img_edit = "/res/image/edit.png";
                var img_del = "/res/image/delete.png";
                var roleStyle = {display: "inline"};
                var editRoleStyle = {display: "none"};
                var info_style = {display: "none"};
                if (index == this.state.selectedIndex) {
                    style = selectedStyle;
                    img_edit = "/res/image/edit_h.png";
                    img_del = "/res/image/delete_h.png";
                } else {
                    img_edit = "/res/image/edit.png";
                    img_del = "/res/image/delete.png"
                }
                var role;
                switch (item.role) {
                    case "owner":
                        role = "创建者";
                        break;
                    case "admin":
                        role = "管理员";
                        break;
                    case "developer":
                        role = "开发者";
                        break;
                    case "observer":
                        role = "观察者";
                        break;
                }
                if (item.role == "owner") {
                    img_edit = null;
                    img_del = null;
                    roleStyle = {display: "inline"};
                    editRoleStyle = {display: "none"};
                    info_style = {display: "none"}
                } else {
                    info_style = {display: "inline-block"}
                }

                if (this.state.level == 4 || this.state.level == 3) {
                    var option = <td style={{width:"25%"}}>
                        <div>
                            <img
                                src={img_edit}
                                style={{cursor:"pointer",marginRight:"10px",float:"left"}}
                                onClick={this.editRole.bind(this,item,index)}
                            />
                            <img
                                src={img_del}
                                onClick={function(){this.removeMember(item)}.bind(this)}
                                style={{cursor:"pointer",float:"left"}}
                            />
                        </div>
                    </td>
                } else {
                    option = <td style={{width:"25%"}}>
                     <span style={info_style}>
                        <span
                            style={{width: "23px",height: "23px",display: "inline-block",marginLeft: "5px",marginTop: "-1px",color: "#EBEBEB"}}>
                            <OverlayTrigger trigger="hover" placement="bottom"
                                            overlay={
                                            <Popover>
                                               只有项目创建者和管理员具有删除和编辑成员的权限
                                            </Popover>}>
                                <i className="fa fa-info-circle"
                                   style={{fontSize:"24px",cursor:"pointer"}}/>
                            </OverlayTrigger>
                        </span>
                     </span>
                    </td>;
                }
                table_item.push(
                    <tr id={"table_item_" + index}
                        key={index}
                        onClick={this.onItemSelected.bind(this,item,index)}
                        style={style}
                    >
                        <td style={{cursor:"pointer",paddingLeft:"20px",width:"25%"}}>{index + 1}</td>
                        <td style={{cursor:"pointer",width:"25%"}}>{item.name}</td>
                        <td id={"role_col_"+ index} style={{cursor:"pointer",width:"25%"}}>
                            <div id={"member_role_"+ index} style={roleStyle}>{role}</div>
                            <div id={"edit_role_"+index} style={editRoleStyle}>
                                <select className="edit_member" id={"edit_role_select_"+index}
                                        default={item.role}
                                        onBlur={()=>{this.hiddenSelect(index)}}
                                >
                                    <option value='admin'>管理员</option>
                                    <option value='developer'>开发者</option>
                                    <option value='observer'>观察者</option>
                                </select>
                                <img src='/res/image/save.png' className='edit_member_save'
                                     onClick={()=>{this.saveEdit(item,index)}}/>
                            </div>
                        </td>
                        {option}
                    </tr>
                )
            }.bind(this));
            this.setState({
                table_item: table_item
            });
        }
        ,
        render: function () {
            if (this.state.level == 4 || this.state.level == 3) {
                var addBtn = <Button bsStyle="primary"
                                     style={{backgroundColor:"#303c40",height: "25px",marginRight: "40px",float:"right",paddingTop: "2px"}}
                                     onClick={this.openAddMemberDlg}
                                     id="add_member">添加
                </Button>;
            } else {
                addBtn = null;
            }
            return (
                <div className="content_pageLeft"
                     style={{width:"100%",background: "url(../res/image/bg.png)",backgroundRepeat: "no-repeat",backgroundSize:"cover"}}>
                    <span className="info_title" style={{paddingLeft:"30px"}}>项目成员信息</span>
                    {addBtn}
                    <div style={{height:"calc(100% - 95px)",width:"100%"}}>
                        <table style={{fontSize:16,width:"100%",background:"#ffffff",marginTop:"20px"}}>
                            <tbody>
                            <tr style={{backgroundColor: "#e3e3e3",opacity: "0.8",borderBottom: "#f2f2f2 1px solid",height: "50px",fontSize: "15px"}}>
                                <th style={{paddingLeft:"20px",width:"25%"}}>编号</th>
                                <th style={{width:"25%"}}>用户名</th>
                                <th style={{width:"25%"}}>角色</th>
                                <th style={{width:"25%"}}>操作</th>
                            </tr>
                            </tbody>
                        </table>
                        <div style={{height:"calc(100% - 10px)",overflowY:"auto"}}>
                            <table style={{fontSize:16,width:"100%",background:"#ffffff"}}>
                                <tbody>
                                {this.state.table_item}
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <AddMemberDlg ref="add_member_dialog" addMember={this.addMember}/>
                </div>
            )
        }

    })
    ;

export default MemberManageTab;